package co.edu.unal.satacredito.rest.auth;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

/**
 * Jersey exception mapper provider that maps instances of {@link RequestProcessingException}
 * to the right response.
 */
@Provider
public class RequestProcessingExceptionMapper implements ExceptionMapper<RequestProcessingException> {

    /**
     * Maps the exception to the response. In case of UNAUTHORIZED status code, we are mapping
     * to the redirect to the login page, passing the current request URI in the {@code redirect} parameter.
     *
     * @param exception exception instance to be mapped
     * @return response the exception got mapped to
     */
    @Override
    public Response toResponse(RequestProcessingException exception) {
        if (Response.Status.UNAUTHORIZED.equals(exception.getStatus())) {
            return Response.seeOther(UriBuilder.fromPath("/login").queryParam("redirect", exception.getUriInfo().getRequestUri()).build()).build();
        } else {
            return Response.status(exception.getStatus()).build();
        }
    }
}
